package suanfa;

public class offer20_2 {
    /*  1 2 3 4
        4 3 2 1
        8 6 7 5   1 endrow 5-1-1=3 2
        6 3 5 8
        5 4 7 2
     逆时针打印矩阵*/
    public static void main(String[] args) {
        int a[][] = {{1, 2, 3, 4}, {4, 3, 2, 1}, {8, 6, 7, 5}, {6, 3, 5, 8}, {5, 4, 7, 2}};
        PrintAll(a, a[0].length, a.length);
    }

    public static void PrintAll(int[][] numbers, int cols, int rows) {
        if (numbers == null || cols == 0 || rows == 0)
            return;
        int start = 0;
        while (cols > start * 2 && rows > start * 2) {
            Print(numbers, cols, rows, start);
            start++;
        }
    }

    public static void Print(int[][] numbers, int cols, int rows, int start) {
        int endX = rows - 1 - start;
        int endY = cols - 1 - start;

        for (int i = start; i <= endX; i++) {
            System.out.print(numbers[i][start] + " ");
        }
        if (start < endY) {
            for (int i = start + 1; i <= endY; i++) {
                System.out.print(numbers[endX][i] + " ");
            }
            if (start < endX) {
                for (int i = endX - 1; i >= start; --i) {
                    System.out.print(numbers[i][endY] + " ");
                }
                System.out.print("");
                if (start < endY - 1) {
                    for (int i = endY - 1; i >= start + 1; --i) {
                        System.out.print(numbers[start][i] + " ");
                    }
                }
            }
        }
    }

}
